package com.leenmvc.core.base.result;


import com.leenmvc.core.utils.thread.ThreadLocalManager;

import java.io.Serializable;

/**
 * 响应数据
 *
 * @author leen
 * @since 1.0.0
 */
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 编码：0 表示成功，其他值表示失败
     */
    private int code = 0;
    /**
     * 消息内容
     */
    private String msg = "success";
    /**
     * 响应数据
     */
    private T data;

    public Result() {
        ThreadLocalManager.setStatusCode(code);
        ThreadLocalManager.put("requestResult", this);
        ThreadLocalManager.closeAllWrapper();
    }

    public Result<T> ok(T data) {
        this.setData(data);
        ThreadLocalManager.setStatusCode(code);
        ThreadLocalManager.put("requestResult", this);
        ThreadLocalManager.closeAllWrapper();
        return this;
    }

    public Result<T> info(String message) {
        this.code = ResultCode.INFO.code;
        this.msg = message;
        ThreadLocalManager.setStatusCode(code);
        ThreadLocalManager.put("requestResult", this);
        ThreadLocalManager.closeAllWrapper();
        return this;
    }

    /**
     * 权限不足
     *
     * @param message
     * @return
     */
    public Result<T> unauthorized(String message) {
        this.code = ResultCode.NO_AUTHORIZED.code;
        this.msg = message;
        ThreadLocalManager.setStatusCode(code);
        ThreadLocalManager.put("requestResult", this);
        ThreadLocalManager.closeAllWrapper();
        return this;
    }

    public Result<T> error(String message) {
        this.code = ResultCode.FAIL.code;
        this.msg = message;
        ThreadLocalManager.setStatusCode(code);
        ThreadLocalManager.put("requestResult", this);
        ThreadLocalManager.closeAllWrapper();
        return this;
    }

    public boolean success() {
        return code == 0 ? true : false;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }


}
